package softtech.app.secretcaller;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class BroadcastListenSms extends BroadcastReceiver {

	public static final String TAG = "LISTENER SMS MESSAGE";
	
	DatabaseHandler db ;
	
	public static String msg_from;
	
	public BroadcastListenSms(){
		super();
		db = null;
		msg_from = "";
	}

	public void onReceive(final Context context, Intent intent) {
		Log.e(TAG, " CO SMS intent ="+ intent.getAction() );
		try{
			if(db == null || db.equals(null)){
				db = new DatabaseHandler(context);
			}
		}catch(Exception e){
			e.printStackTrace();
			return;
		}
		
		int id_login = checkLogin(context);
		if(id_login < 0){
			Log.e(TAG , "ID LOGIN < 0");
			return;
		}
		
		if (intent.getAction()
				.equals("android.provider.Telephony.SMS_RECEIVED")) {
			Bundle bundle = intent.getExtras(); // ---get the SMS message passed
			SmsMessage[] msgs = null;

			if (bundle != null) {
				// ---retrieve the SMS message received---
				Log.e(TAG , "Bundle khac null");
				try {
					Object[] pdus = (Object[]) bundle.get("pdus");
					msgs = new SmsMessage[pdus.length];
					for (int i = 0; i < msgs.length; i++) {
						Log.e(TAG , "Bundle khac null "+i);
						msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
						msg_from = msgs[i].getOriginatingAddress();
						String msg_from_have_plus = msg_from;
						try{
							if(msg_from.contains("+".toString())){
								msg_from_have_plus = msg_from.substring(4);
							}
						}catch(Exception ex){
							ex.printStackTrace();
						}
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss",java.util.Locale.getDefault());
						String last_sms = sdf.format(new Date());
						String msgBody = msgs[i].getMessageBody();
						Log.e(TAG , "phone number = " +msg_from + " , " + msg_from_have_plus );
						DatabaseContact contact = db.getContactLikePhoneNumber(msg_from_have_plus, id_login);
						if(contact==null||contact.equals(null)){
							return;
						}else{
							
							contact.setLastSms(last_sms+ " " + msgBody);
						}
						
						
						Log.e(TAG , msgBody + " " + msg_from);
						
						DatabaseSMS sms = new DatabaseSMS(contact.getPrimaryKey(), contact.getPhoneNumber(), msgBody, DatabaseSMS.RECEIVE);
						sms.setDate(last_sms);
						db.addNewSMS(sms);
						db.updateContactLastCall(contact.getPrimaryKey(), contact);
						
						Intent intent_sms = new Intent(ConstantsFileName.TAG_BROADCAST);
						intent_sms.putExtra(ConstantsFileName.TAG_GET_FLAG , ConstantsFileName.FLAG_RECEIVE_SMS);
						intent_sms.putExtra(DatabaseContact.KEY_PHONE, msg_from);
						intent_sms.putExtra(DatabaseSMS.KEY_CONTENT, msgBody);
						context.sendBroadcast(intent_sms);

						try {

							new Thread() {
								public void run() {
									try {
										sleep(3000);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}finally{
										ControlPhoneAction.deleteSMS(context, msg_from);
									}
								}
							}.start();

						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				} catch (Exception e) {
					 e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * Check Login - (-1) : if not login. - id_login : if logged in.
	 */
	int checkLogin(Context context) {
		int id = -1;
		ToolsSaveFile tsf = new ToolsSaveFile();

		String id_loggedin = tsf.LoadContentFile(context,
				ConstantsFileName.FILE_ID_LOG_IN);

		if (id_loggedin == null || id_loggedin.equals("")
				|| id_loggedin.length() == 0) {

			id = -1;
		} else {
			try {
				id = Integer.parseInt(id_loggedin);

			} catch (Exception e) {
				id = -1;
				e.printStackTrace();
			}
		}

		return id;
	}
	
	
	
}